ନମସ୍କାର,我是Charlie!
在Day22當中我們完成了前端的paypal結帳,而今天我們將完成後端的訂單資料API。
================================◉‿◉=================================
首先是總訂單資料的部分,先在logincheck方法當中新增GET:
@logincheck('POST','GET')
接著在userorder方法當中新增order get的程式碼,把user的order都過濾出來:
if request.method == "GET":
req = request.GET
if "username" not in req:
return R.badRequest("username not found")
username = req["username"]
user = User.objects.filter(name = username)
if not user:
return R.badRequest("user does not exist")
user = user[0]
userorder = Order.objects.filter(user = user)
再來我們要整理一下返回資料的格式,同一個orderno會有一個products的欄位,裡面有這個訂單所有包含的product:
data = []
for order in userorder:
for d in data:
if order.orderno == d["orderno"]:
d["products"].append(order.product.toJson())
d["amount"] += order.amount
break
else:
data.append({
"orderno":order.orderno,
"products":[
order.product.toJson()
],
"username":order.user.name,
"amount":order.amount,
"status":order.status,
"paypal_id":order.paypal_id,
"created_time":order.created_time,
"modified_time":order.modified_time
})
return R.ok({"data":data})
接著做測試,就可以看到同一個訂單內的商品都已經歸到了products裡面:
接著是訂單詳情的部分,首先建立一個url pattern:
url(r'/(?P<orderno>[0-9A-Za-z]{22})$',views.userorder),
接著建立程式碼,過濾出order中符合orderno跟username的Order:
@logincheck('POST','GET')
if request.method == "GET" and orderno:
req = request.GET
if "username" not in req:
return R.badRequest("username not found")
username = req["username"]
user = User.objects.filter(name = username)
if not user:
return R.badRequest("user does not exist")
user = user[0]
userorder = Order.objects.filter(user = user).filter(orderno = orderno)
if not userorder:
return R.badRequest("order does not exist")
data = {}
for order in userorder:
if "orderno" not in data:
product = order.product.toJson()
product["amount"] = order.amount
product["subtotal"] = order.amount * product["price"]
data = {
"id":order.id,
"orderno":order.orderno,
"products":[
product
],
"username":order.user.name,
"amount":order.amount,
"paypal_id":order.paypal_id,
"created_time":order.created_time,
"modified_time":order.modified_time,
"orderStatus":order.status,
"phone":order.user.phone,
}
else:
product = order.product.toJson()
product["amount"] = order.amount
product["subtotal"] = order.amount * product["price"]
data["products"].append(
product
)
data["amount"] += order.amount
print(data)
return R.ok(data)
接著做測試:
就完成了訂單詳情跟總資料的API。
================================◉‿◉=================================
Day23結束了!在今天我們完成了總訂單跟訂單詳情的API,明天我們將完成前端的訂單跟訂單詳情,See ya next day!